import 'dart:async';

import 'package:bxultimate/app/theme/app_theme.dart';
import 'package:bxultimate/app/theme/gaps.dart';
import 'package:bxultimate/data/request/base_request.dart';
import 'package:bxultimate/data/request/organization_request.dart';
import 'package:bxultimate/domain/application/organization/AttendanceClockResultDto.dart';
import 'package:bxultimate/domain/application/organization/AttendanceItemDto.dart';
import 'package:bxultimate/domain/application/organization/PersonAttendanceClickingDto.dart';
import 'package:bxultimate/domain/common/MapLatLonDto.dart';
import 'package:bxultimate/domain/common/result.dart';
import 'package:bxultimate/shared/constant/app_constant.dart';
import 'package:bxultimate/shared/util/util_sp.dart';
import 'package:bxultimate/widgets/app/app_gd_map.dart';
import 'package:bxultimate/widgets/app/app_input.dart';
import 'package:bxultimate/widgets/mk_card_container.dart';
import 'package:bxultimate/widgets/mk_list_cell_item.dart';
import 'package:flutter/material.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:bxultimate/widgets/app/app_input.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart' hide TDInput, TDInputType;

class Attendance extends StatefulWidget {
  final String orgId;

  const Attendance({super.key, required this.orgId});

  @override
  State<Attendance> createState() => _AttendanceState();
}

class _AttendanceState extends State<Attendance> {
  TextEditingController remarkController = TextEditingController();
  AttendanceClockResultDto attendanceClockResultDto = AttendanceClockResultDto();
  bool canClocking = false;
  Timer? _time;
  var _currentDate = '${DateTime.now().hour.toString().padLeft(2, '0')}:'
      '${DateTime.now().minute.toString().padLeft(2, '0')}:'
      '${DateTime.now().second.toString().padLeft(2, '0')}';

  getNowTime() {
    var now = DateTime.now();
    setState(() {
      _currentDate = '${now.hour.toString().padLeft(2, '0')}:'
          '${now.minute.toString().padLeft(2, '0')}:'
          '${now.second.toString().padLeft(2, '0')}';
    });
  }

  List<PersonAttendanceClickingDto> dtoList = [];

  late PersonAttendanceClickingDto currentClocking =
      PersonAttendanceClickingDto();
  MapLatLonDto currentPosition = MapLatLonDto();

  List<String> currentClockingList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getData();
  }

  getData() async {
    dtoList =
        await OrganizationRequest.getPersonAttendanceClockingList(widget.orgId);
    if (dtoList.length > 0) {
      currentClocking = dtoList[0];
    }
    String? devicePosition =
        UtilSp.getString(AppConstant.DEVICE_POSITION, defValue: "");
    print(devicePosition);
    var arr = devicePosition!.split(",");
    currentPosition = await BaseRequest.getLatLonAddress(
        double.parse(arr[1]), double.parse(arr[0]));

    currentClockingList = dtoList.map((e) => e.title!).toList();
    setState(() {});
    checkIsClocking();
  }

  checkIsClocking() async {
     attendanceClockResultDto =
        await OrganizationRequest.getAttendanceClockingAroundAndTimeResult(
            currentClocking.id, currentPosition.lat, currentPosition.lon);
     if(attendanceClockResultDto.resultStauts!){
       canClocking = true;
     }else {
       canClocking = false;
     }
     setState(() {

     });
  }

  _buildBody() {
    const oneSec = Duration(seconds: 1);
    if (_time != null) {
      _time!.cancel();
    }
    _time = Timer.periodic(oneSec, (Timer timer) {
      getNowTime();
    });

    return Padding(
        padding: EdgeInsets.only(
            left: AppTheme.iDefaultPadding, right: AppTheme.iDefaultPadding),
        child: Column(
          children: [
            currentPosition.lat == null ? SizedBox(height: 160,) : Container(
              width: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
              ),
              clipBehavior: Clip.hardEdge,
              height: 160,
              child: AppGdMap(
                point: AppGdMapPoint(
                  icon:
                      'https://minio.sxmbxt.com/static/img/attendance/map_icon.png',
                  latLng: LatLng(double.parse(currentPosition.lat.toString()),double.parse(currentPosition.lon.toString())),
                ),
              ),
            ),
            Gaps.vGap8,
            _buildNav(),
            Gaps.vGap32,
            _buildAttendanceButton(),
          ],
        ));
  }

  selectAttendance() async {
    if(currentClockingList.length == 0){
      return;
    }
    TDPicker.showMultiPicker(context, title: '选择考勤', onConfirm: (selected) {
      setState(() {
        currentClocking = dtoList[selected[0]];
        checkIsClocking();
      });
      Navigator.of(context).pop();
    }, data: [currentClockingList]);
  }

  _buildNav() {
    return MkCardContainer(
      padding: EdgeInsets.symmetric(horizontal: AppTheme.iDefaultPadding / 2),
      margin: EdgeInsets.all(0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          MkListCellItem(
            value: '考勤标题',
            ext: Text(
                currentClocking.id == null ? '暂无考勤' : currentClocking.title!),
            press: selectAttendance,
          ),
          MkListCellItem(
            value: '地址',
            ext: Text('${currentPosition.address}'),
            press: () {},
          ),
          TDInput(
            controller: remarkController,
            leftLabel: '备注',
            leftLabelStyle: TextStyle(fontSize: 14),
            type: TDInputType.special,
            hintText: '请填写签到备注',
            textAlign: TextAlign.end,
            backgroundColor: Colors.transparent,
          ),
        ],
      ),
    );
  }

  addClocking() async {
    Result result = await OrganizationRequest.addClocking({
      "clockingId": attendanceClockResultDto.clockingId,
      "clockingTimeId": attendanceClockResultDto.timeId,//考勤详情中，当前时间所在考勤时间段id
      "lon": currentPosition.lon,
      "lat": currentPosition.lat,
      "address": currentPosition.address,
      "remark": remarkController.text
    });
    if (result.code == AppConstant.RESULT_ERROR) {
      SmartDialog.showNotify(
          msg: result.message!, notifyType: NotifyType.failure);
    } else {
      SmartDialog.showNotify(msg: '签到成功', notifyType: NotifyType.success);
    }

    checkIsClocking();
  }

  _buildAttendanceButton() {
    return ElevatedButton(
      onPressed: canClocking ? addClocking : null,
      style: ButtonStyle(
        minimumSize: MaterialStateProperty.all(Size(150, 150)),
        shape: MaterialStateProperty.all(CircleBorder()),
        backgroundColor: canClocking
            ? MaterialStateProperty.all(Colors.blue)
            : MaterialStateProperty.all(Color(0xFFC0C4CC)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            canClocking ? '签到' : '${attendanceClockResultDto.resultStr == null ?'暂无考勤' : attendanceClockResultDto.resultStr} ',
            style: TextStyle(
                color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
          ),
          Gaps.vGap8,
          Text(
            '${_currentDate}',
            style: TextStyle(color: Colors.white, fontSize: 12),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: _buildBody(),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    if (_time != null) {
      _time!.cancel();
    }
    super.dispose();
  }
}
